package controller

import (
	"fmt"

	. "gddgame.cc/galaxy/common/dsl/web"
	"gddgame.cc/galaxy/core/models"
	"gddgame.cc/galaxy/utils/uuid"

	"gddgame.cc/galaxy/utils/def"
)

func Login(context def.Context, username string, password string) (*models.Manager, error) {
	var manager models.Manager
	var err error
	var ok bool
	if ok, err = models.ManagerModel.Query().Where("=", "username", username).One(&manager); !ok {
		return nil, EmptyExceptionDetail("管理员不存在", err)
	}
	if manager.FormatPassword(password) != manager.Password {
		return nil, ValidException("用户名密码错误")
	}
	manager.Token = uuid.RandomString()
	_, err = models.ManagerModel.PK(manager.Id).Update(map[string]interface{}{
		`token`: manager.Token,
	})
	if err != nil {
		return nil, SystemExceptionDetail("刷新token失败", err)
	}
	return &manager, nil
}

func ValidToken(context def.Context, token string) (*models.Manager, error) {
	var manager models.Manager
	var err error
	var ok bool
	if ok, err = models.ManagerModel.Query().Where("=", "token", token).One(&manager); !ok {
		return nil, EmptyExceptionDetail("管理员不存在", err)
	}
	return &manager, nil
}

func EditPassword(context def.Context, id int, password string) error {
	var manager models.Manager
	var err error
	var ok bool
	fmt.Printf("%#v", id)
	if ok, err = models.ManagerModel.PK(id).One(&manager); !ok {
		return EmptyExceptionDetail("管理员不存在", err)
	}
	manager.Password = manager.FormatPassword(password)
	_, err = models.ManagerModel.PK(id).Update(map[string]interface{}{
		`password`: manager.Password,
	})
	if err != nil {
		return SystemExceptionDetail("密码更新失败", err)
	}
	return nil
}
